//
//  SqliteManager.swift
//  TestProject
//
//  Created by 万想想 on 2020/8/19.
//  Copyright © 2020 edaili. All rights reserved.
//

import UIKit
import SQLite
import SQLite
class SqLiteManger{
    
    static let shareInstance = SqLiteManger.init(sqlPath: Tool.getSavePath() + "/demo.sqlite")
    private var db:Connection?
    init(sqlPath:String) {
        db = try? Connection.init(sqlPath)
        db?.busyTimeout = 5.0
    }
}

extension SqLiteManger{
    func createTable(tableName:String, block: (TableBuilder) -> Void) -> Table? {
        do{
            let table = Table.init(tableName)
            try db?.run(table.create(temporary: false, ifNotExists: true, withoutRowid: false, block: { (builder) in
                block(builder)
            }))
            return table
        }catch(let error){
            debugPrint(error.localizedDescription)
            return nil
        }
    }
    
}

extension SqLiteManger{
    @discardableResult func insert (table:Table?,setters:[Setter]) -> Bool{
        guard let tab = table else {
            return false
        }
        do {
            try db?.run(tab.insert(setters))
            return true
        } catch let error {
            debugPrint(error.localizedDescription)
            return false
        }
    }
    
    func select(table:Table?,select: [Expressible] = [], order: [Expressible] = [], limit: Int? = nil, offset: Int? = nil) -> [Row]? {
        guard var queryTable = table else {
            return nil
        }
        do {
            if select.count != 0{
                queryTable = queryTable.select(select).order(order)
            }else{
                queryTable = queryTable.order(order)
            }
            
            if let lim = limit{
                if let off = offset {
                    queryTable = queryTable.limit(lim, offset: off)
                }else{
                    queryTable = queryTable.limit(lim)
                }
            }
            guard let result = try db?.prepare(queryTable) else { return nil }
            return Array.init(result)
        } catch let error {
            debugPrint(error.localizedDescription)
            return nil
        }
    }
}
